package lego.Moving;

import lego.jbv.Display;
import lego.jbv.Hunger;
import lejos.nxt.Motor;

public class Eat implements Behavior{

	private boolean suppressed = false;
	private Hunger hunger;
	private final int eatTime = 5000;
	private final int startAngle = 70;
	private boolean isEating = false;

	public Eat(Hunger hunger)
	{
		this.hunger = hunger;
		int angle = Motor.B.getPosition();
		Motor.B.rotate(startAngle-angle);
	}
	
	@Override
	public int takeControl() {
		if(Display.getStamina() < 10 && !isEating)
		{
			return 91;
		}
		else if(Display.getStamina() < Display.getStaminaLowBound() && !isEating)
		{
			return 20;
		}
		
		return 0;
	}

	@Override
	public void action() {
		suppressed = false;
		isEating = true;
		Display.setStatus("EATING");
		if(Motor.B.getPosition() > 60)
			Motor.B.rotate(-(Motor.B.getPosition()-20));
		
		long time = System.currentTimeMillis();
		hunger.startEating();

		while(!suppressed && Display.getStamina() < 100 && (System.currentTimeMillis() - time) < eatTime)
		{}
		
		stopEating();
		Thread.yield();
	}
	
	private void stopEating()
	{
		hunger.stopEating();
		if(Motor.B.getPosition() < 30)
			Motor.B.rotate(startAngle-Motor.B.getPosition());
		
		isEating = false;
	}

	@Override
	public void suppress() {
		suppressed = true;
		stopEating();		
	}

}
